package com.demo.function.lambda;

import com.demo.model.entity.es.OrderDetail;
import com.demo.model.entity.es.OrderHeader;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 测试lambda表达式嵌套for循环
 * @author K
 */
public class LambdaList {

    /**
     * lambda表达式处理嵌套for循环
     * @return 商品名称集合
     */
    public List<String> doubleForeach() {
        List<OrderHeader> list = init();

        return list.stream()
                .map(OrderHeader::getDetail)
                .flatMap(Collection::stream)
                .map(OrderDetail::getName)
                .collect(Collectors.toList());
    }

    /**
     * lambda表达式处理嵌套for循环，简化版本
     * @return 商品名称集合
     */
    public List<String> doubleForeach1() {
        List<OrderHeader> list = init();

        return list.stream()
                .flatMap((OrderHeader orderHeader) -> Stream.of(orderHeader.getDetail().toArray(new OrderDetail[]{})))
                .map(OrderDetail::getName)
                .collect(Collectors.toList());
    }

    private List<OrderHeader> init() {
        List<OrderHeader> list = new ArrayList<>();
        long length = 2;
        for (long i = 0; i < length; i++) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(i);
            orderDetail.setName("name" + i);

            OrderHeader orderHeader = new OrderHeader();
            orderHeader.setOrderId(i);
            orderHeader.setDetail(List.of(orderDetail));

            list.add(orderHeader);
        }
        return list;
    }
}
